package com.example.demo.service;

import com.example.demo.model.Emp;
import com.example.demo.reposition.EmpReposition;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

import static org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers.exact;

@Service
@Slf4j
public class EmpService {
    @Autowired
    EmpReposition empReposition;
    static String hname = "emp-name";
    @Autowired
    private RedisTemplate<String, Emp> redisTemplate;

    public List<Emp> findAllEmps(){
        return empReposition.findAll();
    }

    public Optional<Emp> findOne(String name){
        HashOperations<String,String,Emp> hset = redisTemplate.opsForHash();
        if(redisTemplate.hasKey(hname) && hset.hasKey(hname,name)){
            log.info("redis get ");
            return Optional.of(hset.get(hname,name));
        }
        ExampleMatcher ma = ExampleMatcher.matching()
                .withMatcher("name",exact().ignoreCase());
        Optional<Emp> opt = empReposition.findOne(Example.of(Emp.builder().name(name).build(),ma));
        log.info("db data");
        if(opt.isPresent()){
            log.info("put redis");
            hset.put(hname,name,opt.get());
            redisTemplate.expire(hname,10, TimeUnit.MINUTES);
        }
        return opt;
    }
}
